#include "reg52.h"

typedef unsigned int u16;
typedef unsigned char u8;

// individual key
//sbit key1 = P3^1;
//sbit key2 = P3^0;
//sbit key3 = P3^2;
//sbit key4 = P3^3;
//sbit LED1 = P2^0;
//
//#define KEY1_PRESS  1
//#define KEY2_PRESS  2
//#define KEY3_PRESS  3
//#define KEY4_PRESS  4
//#define KEY_UNPRESS 0

// matrix key
#define KEY_MATRIX_PORT P1
#define SMG_A_DP_PORT   P0

u8 NT_CODE[17] = {0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07, 0x7f, 0x6f, 0x77, 0x7c, 0x39, 0x5e, 0x79, 0x71};

void delay_10us(u16 ten_us)
{
	while(ten_us--);
}

// individual key
//// mode = 1 - continous scan
//// mode = 0 - single scan
//u8 key_scan(u8 mode)
//{
//	static key = 1;
//
//	if (mode) key = 1;
//
//	if (key == 1 && (key1 == 0 || key2 == 0 || key3 == 0 || key4 == 0))
//	{
//		delay_10us(1000);
//		key = 0;
//		if (key1 == 0)
//			return KEY1_PRESS;
//		if (key2 == 0)
//			return KEY2_PRESS;
//		if (key3 == 0)
//			return KEY3_PRESS;
//		if (key4 == 0)
//			return KEY4_PRESS;
//	}
//	else if (key1 == 1 && key2 == 1 && key3 == 1 && key4 == 1)
//		key = 1;
//
//	return KEY_UNPRESS;
//}
//
//int main()
//{
//	while (1)
//	{
//		if (key_scan(0) == KEY1_PRESS)
//		{
////			delay_10us(100000);
//			LED1 = !LED1;
//		}
//	}
//
//	return 0;
//}

// matrix key
// line scan
u8 key_matrix_ranks_scan()
{
	u8 key_value = 0;

	KEY_MATRIX_PORT = 0xf7; // the first line is assigned a value of 0, and the rest are all 1
	if (KEY_MATRIX_PORT != 0xf7)
	{
		delay_10us(1000);
		switch(KEY_MATRIX_PORT)
		{
			case 0x77: key_value = 1; break;
			case 0xb7: key_value = 5; break;
			case 0xd7: key_value = 9; break;
			case 0xe7: key_value = 13; break;
		}
	}
	while (KEY_MATRIX_PORT != 0xf7);

	KEY_MATRIX_PORT = 0xfb; // the second line is assigned a value of 0, and the rest are all 1
	if (KEY_MATRIX_PORT != 0xfb)
	{
		delay_10us(1000);
		switch(KEY_MATRIX_PORT)
		{
			case 0x7b: key_value = 2; break;
			case 0xbb: key_value = 6; break;
			case 0xdb: key_value = 10; break;
			case 0xeb: key_value = 14; break;
		}
	}
	while (KEY_MATRIX_PORT != 0xfb);

	KEY_MATRIX_PORT = 0xfd; // the third line is assigned a value of 0, and the rest are all 1
	if (KEY_MATRIX_PORT != 0xfd)
	{
		delay_10us(1000);
		switch(KEY_MATRIX_PORT)
		{
			case 0x7d: key_value = 3; break;
			case 0xbd: key_value = 7; break;
			case 0xdd: key_value = 11; break;
			case 0xed: key_value = 15; break;
		}
	}
	while (KEY_MATRIX_PORT != 0xfd);

	KEY_MATRIX_PORT = 0xfe; // the fourth line is assigned a value of 0, and the rest are all 1
	if (KEY_MATRIX_PORT != 0xfe)
	{
		delay_10us(1000);
		switch(KEY_MATRIX_PORT)
		{
			case 0x7e: key_value = 4; break;
			case 0xbe: key_value = 8; break;
			case 0xde: key_value = 12; break;
			case 0xee: key_value = 16; break;
		}
	}
	while (KEY_MATRIX_PORT != 0xfe);

	return key_value;
}

int main()
{
	u8 key = 0;
	while (1)
	{
		key = key_matrix_ranks_scan();
		if (key != 0)
			SMG_A_DP_PORT = NT_CODE[key - 1];
	}
}